package com.crud.demo1.demos.commons.aop;

import com.crud.demo1.demos.commons.annotation.LimitRequest;
import com.crud.demo1.demos.commons.exception.GlobalException;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * &#064;Description  自定义AOP切面 处理重复请求接口（刷接口）
 * @author zhangning
 * @since 2025/3/1 21:22
 */
@Aspect
@Component
public class LimitRequestAspect {

    private static final ConcurrentHashMap<String, ExpiringMap<String, Integer>> BOOK = new ConcurrentHashMap<>();

    // 定义切入点
    // controller中被@LimitRequest修饰的接口，都被切入，执行请求限制逻辑
    @Pointcut("@annotation(limitRequest)")
    public void excudeSevice(LimitRequest limitRequest) {

    }

    @Around(value = "excudeSevice(limitRequest)", argNames = "joinPoint,limitRequest")
    public Object doAround(ProceedingJoinPoint joinPoint, LimitRequest limitRequest) throws Throwable {

        // 获得request对象
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        if (sra == null) {
            throw new GlobalException("请求路径有误!,错误路径为ra:" + ra);
        }
        HttpServletRequest request = sra.getRequest();
        // 获取Map对象， 如果没有则返回默认值
        // 第一个参数是key， 第二个参数是默认值
        ExpiringMap<String, Integer> uc = BOOK.getOrDefault(request.getRequestURI(), ExpiringMap.builder().variableExpiration().build());
        Integer uCount = uc.getOrDefault(request.getRemoteAddr(), 0);


        if (uCount >= limitRequest.count()) { // 超过次数，不执行目标方法
            throw new GlobalException("接口请求超过次数");
            // return "接口请求超过次数";
            //return JsonResult.error("请求次数过多，已经限制");
        } else if (uCount == 0) { // 第一次请求时，设置有效时间
//            /** Expires entries based on when they were last accessed */
//            ACCESSED,
//            /** Expires entries based on when they were created */
//            CREATED;
            uc.put(request.getRemoteAddr(), uCount + 1, ExpirationPolicy.CREATED, limitRequest.time(), TimeUnit.MILLISECONDS);
        } else { // 未超过次数， 记录加一
            uc.put(request.getRemoteAddr(), uCount + 1);
        }
        BOOK.put(request.getRequestURI(), uc);

        // result的值就是被拦截方法的返回值

        return joinPoint.proceed();

    }
}